package com.ttn.student.service.impl;

import cn.hutool.core.util.NumberUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.ttn.common.core.entity.Result;
import com.ttn.common.core.entity.business.CourseUnitHearingDetails;
import com.ttn.common.core.entity.business.bo.CourseUnitHearingDetailsBO;
import com.ttn.common.core.entity.business.vo.CourseUnitHearingVO;
import com.ttn.common.core.entity.studentrecord.HearingDetailsStudyRecordDetails;
import com.ttn.common.core.entity.studentrecord.LearningProgressRecord;
import com.ttn.common.core.entity.studentrecord.TestStudyRecord;
import com.ttn.common.core.entity.studentrecord.query.TestStudyRecordQuery;
import com.ttn.common.core.entity.studentrecord.vo.TestStudyRecordDetailsVO;
import com.ttn.student.mapper.HearingDetailsStudyRecordDetailsMapper;
import com.ttn.student.openfeign.BusinessFeignService;
import com.ttn.student.service.HearingDetailsStudyRecordDetailsService;
import com.ttn.student.service.LearningProgressRecordService;
import com.ttn.student.service.TestStudyRecordService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class HearingDetailsStudyRecordDetailsServiceImpl extends ServiceImpl<HearingDetailsStudyRecordDetailsMapper, HearingDetailsStudyRecordDetails> implements HearingDetailsStudyRecordDetailsService {
    @Resource
    private HearingDetailsStudyRecordDetailsMapper hearingDetailsStudyRecordDetailsMapper;
    @Resource
    private TestStudyRecordService testStudyRecordService;
    @Resource
    private BusinessFeignService businessFeignService;
    @Resource
    private LearningProgressRecordService learningProgressRecordService;

    @Override
    @Transactional
    public Result saveHearingDetailsStudyRecordDetails(List<HearingDetailsStudyRecordDetails> hearingDetailsStudyRecordDetailsList) {


        TestStudyRecordDetailsVO testStudyRecordDetailsVO = new TestStudyRecordDetailsVO();
        hearingDetailsStudyRecordDetailsList.forEach(hearingDetailsStudyRecordDetails -> {
            if (hearingDetailsStudyRecordDetails.getAnswer().equals(hearingDetailsStudyRecordDetails.getUserAnswer())) {
                hearingDetailsStudyRecordDetails.setAnswerFlag(1);
            } else {
                hearingDetailsStudyRecordDetails.setAnswerFlag(0);
            }
        });
        this.saveBatch(hearingDetailsStudyRecordDetailsList);
        TestStudyRecord testStudyRecord =
                testStudyRecordService.getById(hearingDetailsStudyRecordDetailsList.get(0).getStudyRecordId());
        LambdaQueryWrapper<HearingDetailsStudyRecordDetails> hearingDetailsStudyRecordDetailsLambdaQueryWrapper = new LambdaQueryWrapper<>();
        hearingDetailsStudyRecordDetailsLambdaQueryWrapper.eq(HearingDetailsStudyRecordDetails::getStudyRecordId, hearingDetailsStudyRecordDetailsList.get(0).getStudyRecordId());
        Integer studyNum = Math.toIntExact(this.count(hearingDetailsStudyRecordDetailsLambdaQueryWrapper));
        testStudyRecord.setStudyNum(studyNum);
        testStudyRecordService.updateById(testStudyRecord);
        //计算分数和计算当前超越人数
        if (studyNum.equals(testStudyRecord.getCourseUnitNum())) {
            //获取答对题目数
            LambdaQueryWrapper<HearingDetailsStudyRecordDetails> hearingDetailsStudyRecordDetailsLambdaQueryWrapper1 = new LambdaQueryWrapper<>();
            hearingDetailsStudyRecordDetailsLambdaQueryWrapper1.eq(HearingDetailsStudyRecordDetails::getAnswerFlag, 1);
            hearingDetailsStudyRecordDetailsLambdaQueryWrapper1.eq(HearingDetailsStudyRecordDetails::getStudyRecordId
                    , hearingDetailsStudyRecordDetailsList.get(0).getStudyRecordId());
            Long correctAnswer = this.count(hearingDetailsStudyRecordDetailsLambdaQueryWrapper1);
            testStudyRecord.setCorrectAmount(Math.toIntExact(correctAnswer));
            correctAnswer = correctAnswer * 100;
            testStudyRecord.setScore(NumberUtil.div(correctAnswer, testStudyRecord.getCourseUnitNum()).intValue());

            LambdaQueryWrapper<TestStudyRecord> testStudyRecordLambdaQueryWrapper = new LambdaQueryWrapper<>();
            //获取所有用户数量
            testStudyRecordLambdaQueryWrapper.eq(TestStudyRecord::getCourseUnitId, hearingDetailsStudyRecordDetailsList.get(0).getCourseUnitId());
            testStudyRecordLambdaQueryWrapper.eq(TestStudyRecord::getFinishFlag, 1);
            long countAll = testStudyRecordService.count(testStudyRecordLambdaQueryWrapper);
            if (countAll != 0) {
                //获取超过的用户
                testStudyRecordLambdaQueryWrapper.eq(TestStudyRecord::getFinishFlag, 1);
                testStudyRecordLambdaQueryWrapper.gt(TestStudyRecord::getScore, testStudyRecord.getScore());
                long beyondProportionNum = testStudyRecordService.count(testStudyRecordLambdaQueryWrapper);
                //更新得分和排名
                testStudyRecord.setBeyondProportion(BigDecimal.valueOf(NumberUtil.mul(NumberUtil.sub(1, NumberUtil.div(beyondProportionNum, countAll, 2)), 100)));
            } else {
                testStudyRecord.setBeyondProportion(BigDecimal.valueOf(100));
            }
            testStudyRecordDetailsVO.setTestStudyRecord(testStudyRecord);
            //获取词汇错题集
            hearingDetailsStudyRecordDetailsLambdaQueryWrapper.eq(HearingDetailsStudyRecordDetails::getAnswerFlag, 0);
            testStudyRecordDetailsVO.setHearingDetailsStudyRecordDetails(this.list(hearingDetailsStudyRecordDetailsLambdaQueryWrapper));
            testStudyRecord.setFinishFlag(1);
            testStudyRecordService.updateById(testStudyRecord);
            LambdaQueryWrapper<LearningProgressRecord> learningProgressRecordLambdaQueryWrapper =
                    new LambdaQueryWrapper<>();
            learningProgressRecordLambdaQueryWrapper.eq(LearningProgressRecord::getStudentId, testStudyRecord.getStudentId());
            learningProgressRecordLambdaQueryWrapper.eq(LearningProgressRecord::getCourseUnitId, testStudyRecord.getCourseUnitId());
            LearningProgressRecord learningProgressRecord =
                    learningProgressRecordService.getOne(learningProgressRecordLambdaQueryWrapper);
            learningProgressRecord.setCorrectAmount(testStudyRecordService.queryTotalCorrectAmountByUnitIdId(testStudyRecord.getCourseUnitId(), testStudyRecord.getStudentId()));
//            learningProgressRecord.setFinishFlag(1);
            learningProgressRecordService.updateById(learningProgressRecord);
            return Result.success(testStudyRecordDetailsVO);
        }
        return Result.success();
    }

    @Override
    public Result queryHearingDetailsStudyRecordDetails(TestStudyRecordQuery testStudyRecordQuery) {
        //获取分数最高的一次测试记录
        TestStudyRecordDetailsVO testStudyRecordDetailsVO = new TestStudyRecordDetailsVO();
        LambdaQueryWrapper<TestStudyRecord> testStudyRecordLambdaQueryWrapper = new LambdaQueryWrapper<>();
        testStudyRecordLambdaQueryWrapper.eq(TestStudyRecord::getStudentId, testStudyRecordQuery.getStudentId());
        testStudyRecordLambdaQueryWrapper.eq(TestStudyRecord::getCourseUnitId, testStudyRecordQuery.getCourseUnitId());
        testStudyRecordLambdaQueryWrapper.eq(TestStudyRecord::getUnitTaskType, "2");
        testStudyRecordLambdaQueryWrapper.eq(TestStudyRecord::getFinishFlag, 1);
        testStudyRecordLambdaQueryWrapper.orderByDesc(TestStudyRecord::getScore);
        testStudyRecordLambdaQueryWrapper.last(" limit 1");
        TestStudyRecord testStudyRecord = testStudyRecordService.getOne(testStudyRecordLambdaQueryWrapper);
        if (Objects.nonNull(testStudyRecord)) {
            LambdaQueryWrapper<TestStudyRecord> testStudyRecordLambdaQueryWrapper1 = new LambdaQueryWrapper<>();
            //获取所有用户数量
            testStudyRecordLambdaQueryWrapper1.eq(TestStudyRecord::getUnitTaskType, "2");
            testStudyRecordLambdaQueryWrapper1.eq(TestStudyRecord::getCourseUnitId, testStudyRecordQuery.getCourseUnitId());
            long countAll = testStudyRecordService.count(testStudyRecordLambdaQueryWrapper1);
            if (countAll != 0) {
                //获取超过的用户
                testStudyRecordLambdaQueryWrapper1.eq(TestStudyRecord::getFinishFlag, 1);
                testStudyRecordLambdaQueryWrapper1.gt(TestStudyRecord::getScore, testStudyRecord.getScore());
                long beyondProportionNum = testStudyRecordService.count(testStudyRecordLambdaQueryWrapper1);
                //更新得分和排名
                testStudyRecord.setBeyondProportion(BigDecimal.valueOf(NumberUtil.mul(NumberUtil.sub(1, NumberUtil.div(beyondProportionNum, countAll, 2)), 100)));
            } else {
                testStudyRecord.setBeyondProportion(BigDecimal.valueOf(100));
            }
            testStudyRecordDetailsVO.setTestStudyRecord(testStudyRecord);
            LambdaQueryWrapper<HearingDetailsStudyRecordDetails> hearingDetailsStudyRecordDetailsLambdaQueryWrapper = new LambdaQueryWrapper<>();
            hearingDetailsStudyRecordDetailsLambdaQueryWrapper.eq(HearingDetailsStudyRecordDetails::getStudyRecordId,
                    testStudyRecord.getId());
            hearingDetailsStudyRecordDetailsLambdaQueryWrapper.eq(HearingDetailsStudyRecordDetails::getAnswerFlag, 0);
            testStudyRecordDetailsVO.setHearingDetailsStudyRecordDetails(this.list(hearingDetailsStudyRecordDetailsLambdaQueryWrapper));
        }
        return Result.success(testStudyRecordDetailsVO);
    }

    @Override
    public List<CourseUnitHearingVO> getUnfinishedCourseUnitHearingDetailsList(TestStudyRecord testStudyRecord) {
        List<CourseUnitHearingVO> courseUnitHearingVOList = Lists.newArrayList();

        List<CourseUnitHearingDetailsBO> courseUnitHearingDetailsBOList = hearingDetailsStudyRecordDetailsMapper.getUnfinishedCourseUnitHearingDetailsList(testStudyRecord);

        Map<Integer, List<CourseUnitHearingDetailsBO>> courseUnitHearingDetailMap = courseUnitHearingDetailsBOList.stream().collect(Collectors.groupingBy(CourseUnitHearingDetailsBO::getCourseUnitHearingId));
        courseUnitHearingDetailMap.forEach((k, v) -> {
            CourseUnitHearingVO courseUnitHearingVO = new CourseUnitHearingVO();
            List<CourseUnitHearingDetails> courseUnitHearingDetailsList = new ArrayList<>();
            courseUnitHearingVO.setId(k);
            v.forEach(courseUnitHearingDetailsBO -> {
                courseUnitHearingVO.setCourseUnitId(courseUnitHearingDetailsBO.getCourseUnitId());
                courseUnitHearingVO.setAudioFile(courseUnitHearingDetailsBO.getAudioFile());
                courseUnitHearingVO.setSort(courseUnitHearingDetailsBO.getSort());
                CourseUnitHearingDetails courseUnitHearingDetails = new CourseUnitHearingDetails();
                courseUnitHearingDetails.setId(courseUnitHearingDetailsBO.getId());
                courseUnitHearingDetails.setAnswer(courseUnitHearingDetailsBO.getAnswer());
                courseUnitHearingDetails.setOptionA(courseUnitHearingDetailsBO.getOptionA());
                courseUnitHearingDetails.setOptionB(courseUnitHearingDetailsBO.getOptionB());
                courseUnitHearingDetails.setOptionC(courseUnitHearingDetailsBO.getOptionC());
                courseUnitHearingDetails.setOptionD(courseUnitHearingDetailsBO.getOptionD());
                courseUnitHearingDetails.setQuestionStem(courseUnitHearingDetailsBO.getQuestionStem());
                courseUnitHearingDetails.setCourseUnitHearingId(courseUnitHearingDetailsBO.getCourseUnitHearingId());
                courseUnitHearingDetails.setQuestionNumber(courseUnitHearingDetailsBO.getQuestionNumber());
                courseUnitHearingDetailsList.add(courseUnitHearingDetails);
            });
            courseUnitHearingVO.setCourseUnitHearingDetailsList(courseUnitHearingDetailsList);
            courseUnitHearingVOList.add(courseUnitHearingVO);
        });
        if (courseUnitHearingVOList.size() > 0) {
            courseUnitHearingVOList.sort(Comparator.comparing(CourseUnitHearingVO::getSort));
        }
        return courseUnitHearingVOList;

    }
}
